'''
Created on Mar 23, 2013

@author: Petko
'''
from django.views.generic.base import View
from sententialyzer.settings import SENTENTIALYZER_DEFAULT_GROUP_NAME
from sent.utils import createValidToken, CommonResult, ErrorIds, AccessToken
from sent.utils.result_printer import getPrinter
from sent.model.entities.opinion import ViewEnt
from sent.model.OpinionDBManager import OpinionDBManager
from sqlalchemy.exc import IntegrityError
import re

groupPermissionRegex = re.compile(r"^([a-zA-Z0-9_\+\=\/\.\,\\\!\@\#\$\%\^\&\*\(\)]+):([lm]+)$")
viewIdRegex = re.compile(r"^[a-zA-Z0-9_\+\=\/\.\,\\\!\@\#\$\%\^\&\*\(\)]+$")

class CreateView(View):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        pass
    
    def post(self, *args, **kwargs):
        accessTokenStr = self.request.POST.get('access_token', None)
        viewId = self.request.POST.get('view_id', None)
        group_permissions = self.request.POST.get('group_permissions', None)
        
        cResult = CommonResult()
        
        if accessTokenStr and group_permissions and viewId:
            
            accessToken, error = createValidToken(accessTokenStr, 'view_adm')
            if accessToken:
                groupPermissionsList = group_permissions.split(' ')
                assert isinstance(accessToken, AccessToken)
                validPermissions = True
                groupPermissionsDict = {}
                for groupPermission in groupPermissionsList:
                    m = groupPermissionRegex.match(groupPermission)
                    if m:
                        groupId = m.group(1)
                        permissions = set(m.group(2))
                        groupPermissionsDict[groupId] = permissions
                    else:
                        validPermissions = False
                        break
                
                if validPermissions:
                
                    dbMan = OpinionDBManager(False)
                    try:
                        
                        view = ViewEnt()
                        view.external_id = viewId
                        
                        defaultPerm = groupPermissionsDict.get(SENTENTIALYZER_DEFAULT_GROUP_NAME, [])
                        view.default_perm = "".join(defaultPerm)
                        
                        dbMan.createView(view)
                        
                        dbMan.addViewPermissions(view.id, groupPermissionsDict)
                        
                        cResult.result = view.toPrimitiveDict()
                        
                        dbMan.commitSession()
                        
                        cResult.errorId = ErrorIds.SUCCESS
                    except IntegrityError:
                        dbMan.dbSession.rollback()
                        cResult.errorId = ErrorIds.CONFLICT
                        cResult.result = "View with ID '%s' already exists" % viewId
                    except:
                        dbMan.dbSession.rollback()
                        raise
                else:
                    cResult.errorId = ErrorIds.BADREQUEST
                    cResult.result = "Invalid group permissions"
            else:
                cResult.errorId = ErrorIds.UNAUTHORIZED
                cResult.result = error
        else:
            cResult.errorId = ErrorIds.BADREQUEST
            cResult.result = "Missing parameter"
            
        return getPrinter().printResult(cResult)
    
    